<?php
/**
 * Created by PhpStorm.
 * User: xiao
 * Date: 2017/6/16
 * Time: 上午9:56
 */

namespace app\src\platformApply\logic;


use app\src\account\enmu\AccountEnmu;
use app\src\admin\api\UserApi;
use app\src\base\helper\ExceptionHelper;
use app\src\base\logic\BaseLogic;
use app\src\invite\logic\InviteCodeLogic;
use app\src\platform\emnu\PlatformType;
use app\src\platform\logic\PlatformLogic;
use app\src\platformApply\model\PlatformApply;
use app\src\user\action\DeleteAction;
use app\src\user\action\RegisterAction;
use app\src\user\logic\UcenterMemberLogic;
use think\Db;
use think\exception\DbException;

class PlatformApplyLogic extends BaseLogic
{
    protected function _init()
    {
        $this->setModel(new PlatformApply());
    }

    /**
     * 添加平台申请
     * @param $group_id
     * @param $parent_id
     * @param $entity
     * @return array
     */
    public function addApply($group_id, $parent_id, $entity)
    {
        $data = [
            'group_id' => $group_id,
            'parent_id' => $parent_id,
            'platform_name' => $entity['platform_name'],
            'city_code' => $entity['city_code'],
            'province_code' => $entity['province_code'],
            'preferential_money' => $entity['preferential_money'],
            'apply_info' => $entity['apply_info'],
            'apply_status' => 0,
            'create_time' => NOW_TIME,
            'update_time' => NOW_TIME,
            'status' => 0
        ];

        $result = $this->add($data);
        if($result['status']){
            return $this->apiReturnSuc('success');
        }else{
            return $this->apiReturnErr($result['info']);
        }
    }

    /**
     * 平台申请列表
     * @param array $page
     * @param int $apply_status
     * @return array
     */
    public function applyList($page = ['curpage'=>1,'size'=>10], $apply_status = 0)
    {
        $map = [
            'apply_status' => $apply_status,
            'status' => 0
        ];

        $order = ['create_time' => 'desc'];
        $result = $this->queryWithCount($map, $page, $order);

        return $result;
    }


    /**
     * 通过或否决申请
     * @param $apply_id
     * @param bool $pass
     * @return array
     */
    public function passApply($apply_id, $pass = true)
    {
        //申请中的才能通过
        $result = $this->getInfo(['id' => $apply_id, '	apply_status' => 0, 'status' => 0]);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        if(empty($result['info'])) return $this->apiReturnErr('error apply');
        $apply = $result['info'];
        $apply_info = $this->getApplyInfo($apply['apply_info'], $apply['group_id']);

        $apply_status = $pass ? 1 : 2;
        Db::startTrans();
        $result = $this->save(['id' => $apply_id], ['apply_status' =>  $apply_status, 'update_time' => NOW_TIME]);
        if($result['status']){
            if($pass){
                $account_mobile = $apply_info['account_mobile'];
                $account_psw = $apply_info['account_psw'];
                unset($apply_info['account_mobile'], $apply_info['account_psw']);

                //判断该账号是否已注册，已注册则直接使用该账号
                $map = ['mobile' => $account_mobile, 'country_no' => '+86', 'status' => 1 ];
                $result = (new UcenterMemberLogic)->getInfo($map);
                if(!$result['status']) {
                    Db::rollback();
                    return $this->apiReturnErr($result['info']);
                }
                if(!empty($result['info'])) {
                    $uid = $result['info']['id'];
                }else{
                    //创建账号
                    //查询父级平台邀请码
                    $result = (new InviteCodeLogic)->getInviteCode(AccountEnmu::PLATFORM, $apply['parent_id']);
                    if(!$result['status']){
                        Db::rollback();
                        return $this->apiReturnErr($result['info']);
                    }
                    $invite_code = $result['info']['invite_code'];
                    $result = (new RegisterAction)->registerProcess($account_mobile, $account_mobile, '+86',$account_psw, '', $invite_code);
                    if($result['status']){
                        $map = ['mobile' => $account_mobile, 'country_no' => '+86', 'status' => 1 ];
                        $result = (new UcenterMemberLogic)->getInfo($map);
                        if(!$result['status']) return $this->apiReturnErr($result['info']);
                        $uid = $result['info']['id'];
                    }else{
                        Db::rollback();
                        return $this->apiReturnErr($result['info']);
                    }
                }

                //创建平台
                $entity = [
                    'group_id' => $apply['group_id'],
                    'name' => $apply['platform_name'],
                    'city_code' => $apply['city_code'],
                    'province_code' => $apply['province_code'],
                    'preferential_money' => $apply['preferential_money'],
                    'other_info' => json_encode($apply_info, JSON_UNESCAPED_UNICODE)
                ];

                $PlatformLogic = new PlatformLogic;
                $result = $PlatformLogic->addPlatform($apply['parent_id'], $entity);

                if(!$result['status']) {
                    Db::rollback();
                    (new DeleteAction)->delete($account_mobile);
                    Db::commit();
                    return $this->apiReturnErr($result['info']);
                }

                //添加管理员
                $platform_id = $result['info'];
                $result = $PlatformLogic->setPlatformAdmin($platform_id, $uid);
                if(!$result['status']) {
                    Db::rollback();
                    return $this->apiReturnErr($result['info']);
                }
            }
            Db::commit();

            return $this->apiReturnSuc('success');
        }else{
            Db::rollback();
            return $this->apiReturnErr($result['info']);
        }
    }

    /**
     * 平台申请详情
     * @param $apply_id
     * @return array
     */
    public function applyDetail($apply_id)
    {
        try{
            $map = [
                'apply.id' => $apply_id,
                'apply.status' => 0
            ];

            //获取城市 省
            $model = $this->getModel();
            $result = $model->alias('apply')->field('apply.*,cc.city,cp.province,plat2.name as parent_name')
                ->join(['common_city' => 'cc'], 'apply.city_code = cc.cityID', 'LEFT')->join(['common_province' => 'cp'], 'apply.province_code = cp.provinceID', 'LEFT')
                ->join('__PLATFORM__ plat2', 'apply.parent_id = plat2.id', 'LEFT')
                ->where($map)->find();

            if(empty($result)) return $this->apiReturnErr('error platform apply');

            return $this->apiReturnSuc($result);
        }catch (DbException $ex){
            return $this->apiReturnErr(ExceptionHelper::getErrorString($ex));
        }
    }

    public function getApplyInfo($apply_info, $group_id)
    {

        $ret = [];
        if(empty($apply_info)) return $ret;
        $info = json_decode($apply_info, true);

        if($group_id == PlatformType::CITY_SERVICE){
            $ret = [
                'city_name' => $info['city_name'],
                'idcard_number' => $info['idcard_number'],
                'bank_card_name' => $info['bank_card_name'],
                'bank_card_no' => $info['bank_card_no'],
                'mobile' => $info['mobile'],
                'idcard_front' => $info['idcard_front'],
                'idcard_back' => $info['idcard_back'],
                'business_licence' => $info['business_licence'],
                'account_mobile' => $info['account_mobile'],
                'account_psw' => $info['account_psw']
            ];
        }

        if($group_id == PlatformType::PERSONAL){
            $ret = [
                'name' => $info['name'],
                'idcard_number' => $info['idcard_number'],
                'bank_card_name' => $info['bank_card_name'],
                'bank_card_no' => $info['bank_card_no'],
                'mobile' => $info['mobile'],
                'idcard_front' => $info['idcard_front'],
                'idcard_back' => $info['idcard_back'],
                'account_mobile' => $info['account_mobile'],
                'account_psw' => $info['account_psw']
            ];
        }

        return $ret;
    }
}